/**
 * 工具函数
 */
console.log("utils.js");

/* 判断是否是电话号码 */
function isPhoneNum(num) {
  return /^1[3-9]\d{9}$/.test(num)
}
// toast提示
//type:0为成功 1为失败
//text为显示内容
//interval为显示的时间
function showToast(type, text, interval) {
  let toastElem = document.createElement("div");
  toastElem.className = 'toast-container fdcolumn jscenter aicenter dpflex';
  toastElem.innerHTML = `<div>
   <div class="toast-icon mb16">${type==='succ'?'√':'!'}</div>
   </div>
   <p class="fz14">${text}</p>`;
  document.body.appendChild(toastElem)
  //2S之后删除
  setTimeout(function () {
    toastElem.remove();
  }, interval)
}

/**
 * 添加tab栏
 */
function addTabs(curPage) {
  const tabElem = document.createElement('div');
  tabElem.className = 'tab-container dpflex jsaround aicenter';

  console.log(curPage);
  //设置内容
  tabElem.innerHTML = `
    <a class="tab-item dpflex fdcolumn aicenter ${curPage =='home' ? 'active' : ''}" href="./home.html">
      <i class="iconfont icon-home fz24"></i>
      <span>首页</span>
    </a>
    <a class="tab-item dpflex fdcolumn aicenter ${curPage =='sports' ? 'active' : ''}" href="./run.html">
      <i class="iconfont icon-sports fz24"></i>
      <span>运动</span>
    </a>
    <a class="tab-item dpflex fdcolumn aicenter ${curPage =='mine' ? 'active' : ''}" href="./mine.html">
      <i class="iconfont icon-mine fz24"></i>
      <span>我的</span>
    </a>
  `;
  //添加至页面最后
  document.body.appendChild(tabElem);

}
/**
 * 确认框
 */
function showDialog(text) {
  let toastElem = document.createElement('div') // 创建一个元素节点
  toastElem.id = "dialog"
  toastElem.className = 'toast-container dpflex fdcolumn jscenter aicenter' // 设置类名

  // 设置内容
  toastElem.innerHTML = `  
    <h3>${text}</h3>
    <div class="fz14 mt20">
      <span id="confirmBtn" class="mr16">确定</span>
      <span id="cancelBtn">取消</span>
    </div>
  `;
  // 添加到页面的最后
  document.body.appendChild(toastElem)
}

/**
 * 判断用户是否是登录状态
 */
function isLogin() {
  let userId = window.localStorage.getItem('userId') // 获取本地存储的id
  if (!userId) {
    window.location.href = "./login.html"
  }
}

/* 获取年月日 */
function getDate(time) {
  let date = new Date(time)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  let d = date.getDate()
  return [y, m, d].map(function (v) {
    return padZero(v)
  }).join('-')
}

//小于0补0
function padZero(n) {
  return n < 10 ? '0' + n : n;
}

//顶部导航栏
function addTopNav(curPage) {
  // 1. 创建一个div
  const topNav = document.createElement('ul')

  // 2. 添加几个类名
  topNav.className = 'top-nav dpflex aicenter'

  // 3. 往里面填入html
  topNav.innerHTML = `
    <li class="top-nav-item flex1"><a class="nav-link ${curPage =='run' ? 'active' : ''}" href="./run.html">跑步</a></li>
    <li class="top-nav-item flex1"><a class="nav-link ${curPage =='ride' ? 'active' : ''}" href="./ride.html">骑行</a></li>
    <li class="top-nav-item flex1"><a class="nav-link ${curPage =='course' ? 'active' : ''}" href="./course.html">课程训练</a></li>
  `
  // 4. 通过dom操作， 放入页面中
  document.body.appendChild(topNav)
}

/* 格式化时间：把 秒 转为 时分秒 */
function formatTime(timer) {
  let s = timer % 60 // 计算秒
  let m = (Math.floor(timer / 60)) % 60 // 计算分
  let h = (Math.floor(timer / 3600)) // 计算小时

  return [h, m, s].map(function (v) {
    return padZero(v)
  }).join(':')
}

/* 
  在地图上绘制标记的点
*/
function addMarker(map, point, iconName) { // 创建图标对象   
  // 创建一个icon对象
  var myIcon = new BMap.Icon(iconName, new BMap.Size(45, 45), {
    // 配置对象
    anchor: new BMap.Size(15, 30), // 设置偏移大小
    imageSize: new BMap.Size(30, 32) // 设置图片大小  
  })
  // 插件一个标记对象
  var marker = new BMap.Marker(point, {
    icon: myIcon
  })
  // 把这个标记添加到地图中
  map.addOverlay(marker);
}

/**
 * 绘制线条
 */
function drawLine(map, curPoint, nextPoint) {
  // 定义线条对象
  const polyline = new BMap.Polyline([
    new BMap.Point(curPoint.lng, curPoint.lat),
    new BMap.Point(nextPoint.lng, nextPoint.lat)
  ], {
    strokeColor: "blue", // 线条颜色
    strokeWeight: 6, // 线条宽度
  });
  map.addOverlay(polyline) // 把线条放到地图上 
}


/* 
  根据经纬度计算距离
    startPoint:  起点 
    curPoint:  终点
*/
function calcDistance(startPoint, curPoint) {
  let lat1 = startPoint.lat
  let lng1 = startPoint.lng

  let lat2 = curPoint.lat
  let lng2 = curPoint.lng

  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s.toFixed(2) // 单位千米
}

/* 计算配速函数 
  d： 距离
  s： 时间
*/
function calcPace(d, s) {
  let distance = d
  let spendTime = s / 60
  if (distance > 0 && spendTime > 0) {
    let pace = parseFloat(spendTime / distance)
    let m = Math.floor(pace)
    let s = ((pace - m) * 60).toFixed(0)
    return `${m}'${s}"`
  }
  return "--"
}

/* 计算卡路里 */
function calCalorie(miles) {
  if (miles > 0) {
    let calorie = 60 * miles * 1.036;
    return calorie.toFixed(2)
  }
  return "--"
}

/* 挂在window上 */
window.utils = {
  isPhoneNum: isPhoneNum,
  showToast: showToast,
  addTabs: addTabs,
  showDialog: showDialog,
  isLogin: isLogin,
  getDate: getDate,
  padZero: padZero,
  addTopNav: addTopNav,
  formatTime: formatTime,
  addMarker: addMarker,
  drawLine: drawLine,
  calcDistance: calcDistance,
  calcPace: calcPace,
  calCalorie: calCalorie,
}